package com.jair.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jair.business.mapper.InterfaceInfoMapper;
import com.jair.business.model.dto.Interface.InterfaceInfoAddRequest;
import com.jair.business.model.dto.Interface.InterfaceInfoQueryRequest;
import com.jair.business.model.dto.Interface.InterfaceInfoUpdateRequest;
import com.jair.business.model.entity.InterfaceInfo;
import com.jair.business.model.entity.User;
import com.jair.business.model.vo.InterfaceStatis;
import com.jair.business.service.InterfaceInfoService;
import com.jair.business.service.UserService;
import com.jair.common.constant.bizz.ErrorCode;
import com.jair.common.exception.BusinessException;
import com.jair.common.reponse.DeleteRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
* @author 20654
* @description 针对表【interface_info(接口信息)】的数据库操作Service实现
* @createDate 2025-08-02 21:44:03
*/
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
    implements InterfaceInfoService{

    @Resource
    private UserService userService;
    @Resource
    private InterfaceInfoMapper interfaceInfoMapper;

    @Override
    public Boolean createInterface(InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验
//        this.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = this.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return result;
    }

    @Override
    public Boolean removeInterfaceById(DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = this.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return this.removeById(id);
    }

    @Override
    public Boolean updateInterfaceById(InterfaceInfoUpdateRequest interfaceInfoUpdateRequest, HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
//        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = this.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return this.updateById(interfaceInfo);
    }

    @Override
    public List<InterfaceInfo> listInterface(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        if(StringUtils.isEmpty(interfaceInfoQuery.getName())){
            interfaceInfoQuery.setName(null);
        }
        if (StringUtils.isEmpty(interfaceInfoQuery.getDescription())){
            interfaceInfoQuery.setDescription(null);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        return this.list(queryWrapper);
    }

    @Override
    public Page<InterfaceInfo> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String description = interfaceInfoQuery.getDescription();
        // description 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(interfaceInfoQuery.getName())){
            queryWrapper.like("name", interfaceInfoQuery.getName());
        }
        if (StringUtils.isNotEmpty(interfaceInfoQuery.getDescription())){
            queryWrapper.like("description", interfaceInfoQuery.getDescription());
        }
        if (StringUtils.isEmpty(interfaceInfoQueryRequest.getReUseType())) {
            queryWrapper.eq("status", 1);
        }
        queryWrapper.orderByDesc("createTime");
        Page<InterfaceInfo> page = this.page(new Page<>(current, size), queryWrapper);
        //查找接口统计信息
        List<InterfaceInfo> records = page.getRecords();
        //查询接口表
        InterfaceStatis interfaceStatic = interfaceInfoMapper.getStatistic();
        //查询接口用户记录表
        Integer invokeTotal = interfaceInfoMapper.getInvokeTotal();
        interfaceStatic.setInvokeTotal(invokeTotal);
        records.stream().forEach(item -> {
            interfaceStatic.setInvokeCount(interfaceInfoMapper.getInvokeCount(item.getId()));
            item.setInterfaceStatis(interfaceStatic);
        });
        return page ;
    }


}




